package com.bml.client.secret.demo.completable;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CompletableFutureDemo1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + ":开始执行");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (new Random().nextInt(100) % 2 == 0) {
                int a = 12 / 0;
            }
            System.out.println(Thread.currentThread().getName() + ":执行结束");
            return "成功执行";
        });

        future.whenComplete((s, throwable) -> {
            System.out.println(s + " 执行完成");
        });
        future.exceptionally(ex -> {
            System.out.println("执行出错:" + ex);
            return "异常:" + ex;
        });

        System.out.println(future.get());

    }
}
